package com.coocaa.aries.jmeter.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @author : bijiahao
 * @date : 2019/4/1.
 * @description: jmeter 命令 工具类
 */
public class CmdUtil {
    private static Logger log = LoggerFactory.getLogger(CmdUtil.class);

    /**
     * 获取命令
     * <code></code>
     *
     * @param jmxFilePath
     * @param jtlFilePath
     * @param outputDir
     * @return
     */
    public static String getJmeterCmd(String jmxFilePath, String jtlFilePath, String outputDir) {
        StringBuilder cmd = new StringBuilder();
        cmd.append("sh jmeter -n -t ")
                .append(jmxFilePath)
                .append(" -l ")
                .append(jtlFilePath)
                .append(" -e -o ")
                .append(outputDir);
        return cmd.toString();
    }


    public static String checkJmeterReady(String jmeterBinPath) throws Exception {
        String cmd = "sh jmeter -v";
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(cmd, null, new File(jmeterBinPath));
        return readInfo(process);
    }


    public static String checkPhantomJsReady() throws Exception {
        String cmd = "phantomjs -v";
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(cmd);
        return readInfo(process);

    }

    private static String readInfo(Process process) {
        InputStream inputStream = process.getInputStream();
        BufferedReader reader = null;
        String line;
        StringBuilder info = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            while ((line = reader.readLine()) != null) {
                info.append(line);
            }
            return info.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            process.destroy();
        }
    }


    public static void main(String[] args) throws Exception {
//           String infpo = checkJmeterReady("/Users/bijiahao/develop/jmeter/apache-jmeter-3.3/bin");
        String infpo = checkPhantomJsReady();

        System.out.println(infpo);
    }

}
